﻿using System;
using System.Collections.Generic;

namespace Jayden.Dll.Web.Styles
{
	public class CssProperties : List<CssProperty>
	{
		public delegate void CssPropertiesChanged(object source, EventArgs args);
		public event CssPropertiesChanged Change;

		public CssProperties() { }
		public CssProperties(string style)
		{
			if (style != null)
			{
				string[] properties = style.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string property in properties)
				{
					int index = property.IndexOf(':');
					string key = property.Substring(0, index);
					string value = property.Substring(index + 1);
					Add(key, value);
				}
			}
		}

		public CssProperty Add(string key, string value)
		{
			CssProperty property = new CssProperty(key, value);
			Add(property);
			if (Change != null)
				Change(this, EventArgs.Empty);
			return property;
		}

		public int CheckValidity()
		{
			int version = 0;
			foreach (CssProperty p in this)
				version = Math.Max(version, p.CheckValidity());
			return version;
		}

		public string this[string key]
		{
			get
			{
				for (int c = Count - 1; c >= 0; c--)
				{
					CssProperty property = this[c];
					if (property.Name.Equals(key))
						return property.Value;
				}
				return null;
			}
			set
			{
				for (int c = Count - 1; c >= 0; c--)
				{
					CssProperty property = this[c];
					if (property.Name.Equals(key))
					{
						property.Value = value;
						if (Change != null)
							Change(this, EventArgs.Empty);
						return;
					}
				}
				Add(key, value);
				if (Change != null)
					Change(this, EventArgs.Empty);
			}
		}

		public override string ToString() { return string.Concat(this); }
	}
}
